package com.laycoding.common.util;

import io.netty.util.internal.StringUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ZkUtils {

    public static CuratorFramework getClient(){
        String connStr = "192.168.242.128:2181";
        CuratorFramework cur= CuratorFrameworkFactory.builder()
                .connectString(connStr)
                .connectionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000,3))
                .build();
        cur.start();
        return cur;
    }

    public static String getData(CuratorFramework client,String path) throws Exception {
        Stat stat = client.checkExists().forPath(path);
        if (stat!= null){
            byte[] bytes = client.getData().forPath(path);
            String s = new String(bytes);
            return s;
        }
        return null;
    }

    public static List<String> listService(CuratorFramework client,String path,String name) throws Exception {
        Stat stat = client.checkExists().forPath(path);

        List<String> serviceList = new ArrayList<>();

        if (stat!= null){
            List<String> strings = client.getChildren().forPath(path);
            for (String string : strings) {
                String dataPath = path +"/"+string;
                byte[] bytes = client.getData().forPath(dataPath);
                String s = new String(bytes);
                if (Objects.equals(s,name)){
                    serviceList.add(string);
                }
            }
        }
        return serviceList;
    }

    public static Boolean resgistyService(CuratorFramework client,String serviceName,String data) throws Exception {
        Stat stat = client.checkExists().forPath(serviceName);
        if (stat!= null){
            client.delete().forPath(serviceName);
        }
        client.create().forPath(serviceName,data.getBytes());
        return true;
    }
}
